<template>
  <view class="login-page">
    <view class="card">
      <text class="title">账号登录</text>
      <input class="ipt" placeholder="邮箱或手机号" v-model="form.username" />
      <input class="ipt" placeholder="密码" password v-model="form.password" />
      <button class="btn" @click="login">登录</button>
      <button class="btn ghost" @click="toRegister">注册</button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue'

const API_BASE_URL = 'http://localhost:3001'
const form = ref({ username: '', password: '' })

const login = async () => {
  if (!form.value.username || !form.value.password) {
    return uni.showToast({ title: '请输入邮箱/手机号和密码', icon: 'none' })
  }
  try {
    const res = await uni.request({
      url: `${API_BASE_URL}/api/auth/login`,
      method: 'POST',
      data: form.value,
      header: { 'content-type': 'application/json' }
    })
    const user = res?.data as any
    if (!user || !user.id) throw new Error('登录失败')
    
    // 登录成功后，获取最新的用户信息（包括头像）
    const profileRes = await uni.request({
      url: `${API_BASE_URL}/api/users/${user.id}`,
      method: 'GET'
    })
    const latestUser = profileRes?.data as any
    if (latestUser) {
      // 使用最新的用户信息更新本地存储
      uni.setStorageSync('user', latestUser)
    } else {
      // 如果获取失败，使用登录返回的信息
      uni.setStorageSync('user', user)
    }
    
    uni.showToast({ title: '登录成功', icon: 'success' })
    setTimeout(() => {
      uni.switchTab({ url: '/pages/mine/index' })
    }, 400)
  } catch (e) {
    uni.showToast({ title: '登录失败', icon: 'none' })
  }
}

const toRegister = () => {
  uni.navigateTo({ url: '/pages/auth/register' })
}
</script>

<style>
.login-page { min-height: 100vh; display: flex; align-items: center; justify-content: center; background: #f6f7f9; }
.card { width: 86%; background: #fff; padding: 40rpx 34rpx; border-radius: 16rpx; box-shadow: 0 6rpx 24rpx rgba(0,0,0,0.06); }
.title { font-size: 36rpx; font-weight: 600; color: #333; margin-bottom: 30rpx; display: block; }
.ipt { height: 86rpx; background: #f5f6f7; border-radius: 12rpx; padding: 0 22rpx; margin-bottom: 20rpx; }
.btn { height: 86rpx; background: #007AFF; color: #fff; border: none; border-radius: 12rpx; margin-top: 10rpx; }
.btn.ghost { background: #eef1f5; color: #333; }
</style>



